package com.cxw.healthserver.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.cxw.healthserver.entity.Disease
import com.cxw.healthserver.entity.Resident
import com.cxw.healthserver.entity.User
import com.cxw.healthserver.mapper.ResidentMapper
import com.cxw.healthserver.response.BaseResponse
import com.cxw.healthserver.response.RemotePageDataBean
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import org.json.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @createTime 2024/6/23 19:57
 * @author 崔兴旺
 * @description
 */
@Service
class ResidentService : BaseService<Resident>() {
    @Autowired
    private lateinit var residentMapper: ResidentMapper

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    fun saveResident(username: String, jsonStr: String): BaseResponse<Any> {
        val jsonObject = JSONObject(jsonStr)
        val idNumber = jsonObject.optString("idNumber", "")
        if (idNumber.isNullOrBlank()) {
            return BaseResponse.fail("居民中缺少idNumber")
        }
        var resident = residentMapper.selectOne(QueryWrapper<Resident>().eq("username", username).eq("idNumber", idNumber))
        var isAdd = false
        if (resident == null) {
            resident = Resident()
            isAdd = true
        }
        resident.idNumber = idNumber
        resident.username = username
        resident.realname = jsonObject.getString("name")
        resident.classifyCode = jsonObject.getString("classifyCode")
        resident.diseaseList = jsonObject.getJSONArray("diseaseTag")?.map {
            val code = (it as JSONObject).getString("code")
            val description = it.getString("description")
            Disease(code, description)
        }?.toMutableList()
        resident.json = jsonStr

        val rows = if (isAdd) {
            residentMapper.insert(resident)
        } else {
            residentMapper.updateById(resident)
        }
        if (rows >= 0) {
            return BaseResponse.success(null)
        }
        return if (isAdd) {
            BaseResponse.fail("新增居民失败,rows:${rows}")
        } else {
            BaseResponse.fail("更新居民失败,rows:${rows}")
        }
    }

    fun findResident(username: String, idNumber: String): BaseResponse<JsonNode> {
        val resident = residentMapper.selectOne(createQueryWrapper(username, idNumber))
        if (resident == null) {
            return BaseResponse.success(null)
        }
        return BaseResponse.success(objectMapper.readTree(resident.json))
    }

    fun queryResidentList(user: User, pageNum: Long, pageSize: Long, realName: String?, classify: Int?, diseaseTags: String?, signState: Int?, isHealthdoc: Boolean?): BaseResponse<RemotePageDataBean<JsonNode>> {
        val queryWrapper = QueryWrapper<Resident>().eq("username", user.username)
        println("pageNum:${pageNum}\tpageSize:${pageSize}\trealName:${realName}\tclassify:${classify}\tdiseaseTags:${diseaseTags}\tsignState:${signState}\tisHealthdoc:${isHealthdoc}")
        if (!realName.isNullOrBlank()) {
            queryWrapper.and { qr -> qr.like("idNumber", realName).or { qr -> qr.like("realname", realName) } }
        }
        if (classify != null) {
            queryWrapper.eq("classifyCode", classify)
        }
        if (!diseaseTags.isNullOrBlank()) {
            val list = diseaseTags.split(",")
            list.forEach {
                queryWrapper.apply("JSON_CONTAINS(diseaseList, '{\"code\": \"${it}\"}')")
            }
        }
        if (signState != null) {
            // TODO: 查询签约状态
            /**
             * "未签约" -> 0
             * "已签约" -> 1
             * "签约过期" -> 2
             */
            queryWrapper.eq("signState", signState)
        }

        if (isHealthdoc != null) {
            //查询建档状态
            queryWrapper.eq("hasArchive", if (isHealthdoc == true) {
                1
            } else {
                0
            })
        }
        val page = Page<Resident>(pageNum, pageSize)

        queryWrapper.orderByDesc("updateTime")

        val resultPage = residentMapper.selectPage(page, queryWrapper)

        val jsonObjects = resultPage.records.map { resident ->
            objectMapper.readTree(resident.json).let {
                (it as ObjectNode).apply {
                    this.put("isHealthdoc", resident.hasArchive == 1)
                    this.put("signState", resident.signState)
                }
            }
        }

        return BaseResponse.success(
            RemotePageDataBean(
                resultPage.current,
                resultPage.size,
                resultPage.total,
                resultPage.pages,
                jsonObjects
            )
        )
    }

    /**
     * 将居民记录为:有档案
     */
    fun recordHasArchive(username: String, idNumber: String) {
        val resident = residentMapper.selectOne(createQueryWrapper(username, idNumber))
        resident?.let {
            resident.hasArchive = 1
            residentMapper.updateById(resident)
        }
    }


    /**
     * 将居民记录为:已签约
     */
    fun recordHasSignInfo(username: String, idNumber: String) {
        val resident = residentMapper.selectOne(createQueryWrapper(username, idNumber))
        resident?.let {
            resident.signState = 1
            residentMapper.updateById(resident)
        }
    }
}